import React, { Component, createRef } from 'react'
import { Toast } from 'antd-mobile'

class GoodFood extends Component {
  moreRef = createRef()
  page = 2

  componentDidMount() {
    this.intersectionObserver = new IntersectionObserver(async (entries) => {
      // 如果 intersectionRatio 为 0，则目标在视野外，
      // 我们不需要做任何事情。
      if (entries[0].intersectionRatio <= 0) return
      // 加载更多新数据
      // console.log(entries)
      let ret = await this.props.goodFoodList(this.page)
      if (ret.length > 0) {
        this.page++
      } else {
        Toast.info('没有更多新数据了！')
      }
    })
    // 开始监听
    this.intersectionObserver.observe(this.moreRef.current)
  }
  componentWillUnmount() {
    // 停止监听
    this.intersectionObserver.unobserve(this.moreRef.current)
  }

  render() {
    const { data = [] } = this.props
    return (
      <div className="home-good-food">
        <div className="title">精品好菜</div>
        <div className="item-box">
          {data.map((item) => (
            <dl key={item.id}>
              <dt>
                <img src={item.img} title={item.name} />
              </dt>
              <dd>
                <h3>{item.name}</h3>
                <p>1000浏览 2000收藏</p>
              </dd>
            </dl>
          ))}
        </div>
        <div ref={this.moreRef}>加载更多数据</div>
      </div>
    )
  }
}

export default GoodFood
